package com.easidea.tim.dao.finance;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.Restrictions;
import org.springside.core.dao.extend.HibernateEntityExtendDao;

import com.easidea.tim.dao.system.orgnization.StaffDAO;
import com.easidea.tim.entity.customer.Customer;
import com.easidea.tim.entity.finance.DueFromSummary;
import com.easidea.tim.entity.saleorder.SaleOrder;
import com.easidea.tim.entity.system.orgnization.Staff;
import com.easidea.tim.util.DateUtil;
import com.easidea.tim.util.Page;
import com.easidea.tim.util.ParamsUtilities;

public class DueFromSummaryDao extends HibernateEntityExtendDao<DueFromSummary> {
	private StaffDAO staffDao;
	
	/**
	 * @return the staffDao
	 */
	public StaffDAO getStaffDao() {
		return staffDao;
	}

	/**
	 * @param staffDao the staffDao to set
	 */
	public void setStaffDao(StaffDAO staffDao) {
		this.staffDao = staffDao;
	}

	public DueFromSummary getDueFromSummaryByCustomerId(long customerId) {
		Criteria ca = this.createUnDeletedCriteria();
		ca.add(Restrictions.eq("customer.id", customerId));
		return (DueFromSummary) ca.uniqueResult();
	}

	@SuppressWarnings("unchecked")
	public Page getDueFromSummarByCustomer(long customerId,
			String responer, Date startDate,Date endDate, Page page) {
		Page resultPage = null;
		String select = "";
		String where = "";
		String groupby = "";
		select = " select c.name as customerName,'' as responer, c.bizTel1,c.staff.name as salesName,"
			+ " sum(s.moneyNum)  as amount,d.payed as payed,c.id as customerId  from "
			+ SaleOrder.class.getName() + " as s , "
			+ Customer.class.getName() + " as c , "
			+ DueFromSummary.class.getName() + " as d   ";

	where = " where s.customer.id = c.id and d.customer.id = c.id ";
	groupby = " group by c.name";
	if (customerId  != -1) {
		where += " and c.id = " + customerId;
	}
	if (startDate != null && endDate != null) {
		where += " and s.createTime>= '"+DateUtil.formatDateTime(DateUtil.getStartTime(startDate)) +"' and s.createTime <= '" + DateUtil.formatDateTime(DateUtil.getEndTime(endDate)) +"'";
	}		
		String hql = select + where + groupby;
		Query q1 = this.getSession().createQuery(hql);
		Integer totalNum = q1.list().size();
		int startIndex = Page.getStartOfPage(page.getCurrentPageNo(), page
				.getPageSize());
		if (totalNum > 0) {
			q1.setFirstResult(startIndex);
			q1.setMaxResults(page.getPageSize());
			List<Object[]> ls = (List<Object[]>) q1.list();
			resultPage = new Page(startIndex, totalNum, page.getPageSize(), ls);
			resultPage.setCurrentPageNo(page.getCurrentPageNo());
		} else {
			resultPage = new Page(startIndex, totalNum, page.getPageSize(),
					new ArrayList());
			resultPage.setCurrentPageNo(page.getCurrentPageNo());
		}
		return resultPage;
	}

  @SuppressWarnings("unchecked")
public Page getDueFromSummarBySalesStaff(String salesStaff, Date startDate,Date endDate,Page page) {
		Page resultPage = null;
		String select = "";
		String where = "";
		String groupby = "";
		select = " select c.name as name, c.creditLimit.currentCreditLimit, "
			+ " sum(d.amount)  as amount,sum(d.payed) as payed from "
			+ Staff.class.getName() + " as c , "
			+ DueFromSummary.class.getName() + " as d   ";

	where = " where d.sales.id = c.id ";
	groupby = " group by c.username ";
	if (salesStaff != null && !salesStaff.equals("")) {
		where += " and c.username = '" + ParamsUtilities.dealWithReservedSqlChar(salesStaff) + "'";
	}
	if (startDate != null && endDate != null) {
		where += " and d.createTime>= '"+DateUtil.formatDateTime(DateUtil.getStartTime(startDate)) +"' and d.createTime <= '" + DateUtil.formatDateTime(DateUtil.getEndTime(endDate)) +"'";
	}		
		String hql = select + where + groupby;
		Query q1 = this.getSession().createQuery(hql);
		Integer totalNum = q1.list().size();
		int startIndex = Page.getStartOfPage(page.getCurrentPageNo(), page
				.getPageSize());
		if (totalNum > 0) {
			q1.setFirstResult(startIndex);
			q1.setMaxResults(page.getPageSize());
			List<Object[]> ls = (List<Object[]>) q1.list();
			resultPage = new Page(startIndex, totalNum, page.getPageSize(), ls);
			resultPage.setCurrentPageNo(page.getCurrentPageNo());
		} else {
			resultPage = new Page(startIndex, totalNum, page.getPageSize(),
					new ArrayList());
			resultPage.setCurrentPageNo(page.getCurrentPageNo());
		}
		return resultPage;
  }
  
  /**
	 * 保存或更新某客户应收款总额
	 * @author Harrison
	 * @param saleOrder
	 * @return
	 */
	
  public  DueFromSummary saveDueFromSummary(SaleOrder saleOrder) {
		DueFromSummary summary = null;
		summary = getDueFromSummaryByCustomerId(saleOrder.getCustomer().getId());
		if (summary == null) {
			summary = new DueFromSummary();
		}
		summary.setAmount(summary.getAmount() == null ?(0+saleOrder.getMoneyNum().doubleValue()): (summary.getAmount() + saleOrder.getMoneyNum().doubleValue()));
		summary.setPayed(summary.getPayed() == null ? 0.0 : summary.getPayed());
		summary.setCustomer(saleOrder.getCustomer());//销售订单对应的客户
		summary.setSales(staffDao.getStaffbyName(saleOrder.getCreator()));//录入销售订单的销售员
		getHibernateTemplate().saveOrUpdate(summary);
		return summary;
	}
}
